package com.awspaas.user.apps.processforsap.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListener;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;

import java.util.List;

public class CO004CreateValidate extends InterruptListener implements InterruptListenerInterface {
    @Override
    public boolean execute(ProcessExecutionContext ctx) throws Exception {
        ProcessInstance processInstance = ctx.getProcessInstance();
        BO boMain = ctx.getBO("BO_EU_SAP_CO004");
        //获取公司代码
        String bukrs = boMain.getString("BUKRS");
        //获取AUART订单类型
        String auart = boMain.getString("AUART");
        //获取订单编号
        String aufnr = boMain.getString("AUFNR");

        if (bukrs.equals("FH00")){
            if (auart.equals("Z100")||auart.equals("Z200")){
                if (aufnr.startsWith("RD")){

                }else{
                    throw new BPMNError("0331","请输入以RD为开头的订单编号");
                }
            }else{
                throw new BPMNError("0331","当公司代码为:"+bukrs+"时，订单类型只能选择Z100或Z200！");
            }

        }else if (bukrs.equals("FS00")){
            if (auart.equals("Z101")||auart.equals("Z201")){
                if (aufnr.startsWith("YF")){

                }else{
                    throw new BPMNError("0331","请输入以YF为开头的订单编号");
                }
            }else{
                throw new BPMNError("0331","当公司代码为:"+bukrs+"时，订单类型只能选择Z101或Z201！");
            }
        }



        String zdjlx= boMain.getString("ZDJLX");
        if ("0".equals(zdjlx)){
            String sapSql = "select AUART,AUFNR,KTEXT,PRCTR,TO_DATE(USER7, 'YYYY-MM-DD') USER7 ,TO_DATE(USER8, 'YYYY-MM-DD') USER8,ZZAUFEX from SAP_AUFK where user7 !='00000000' and AUFNR='"+aufnr+"'";
            String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
            RDSAPI api = SDK.getCCAPI().getRDSAPI(rdsId);
            RowMap rowMap = api.getMap(sapSql);
            if (rowMap!=null){
                throw new BPMNError("0331","SAP中已存在编码为:"+aufnr+"的订单编号，请勿重复发起！");
            }
            List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_CO004").addQuery("AUFNR=",aufnr).addQuery("BINDID!=",processInstance.getId()).list();
            if (list!=null && list.size()>0){
                throw new BPMNError("0331","已存在编码为:"+aufnr+"的订单编号，请勿重复发起！");
            }
            return true;
        }
        return true;
    }
}
